import { PageContainer } from '@ant-design/pro-components';
import { useEffect, useState } from 'react';
import { Button, Modal, message, Space, Tree } from 'antd';
import type { TreeProps } from 'antd';
import { addMenu, deleteMenu, editMenu, getMenuTree } from '@/services/menu';
import { DownOutlined } from '@ant-design/icons';
import AddOrEditMenuModal from './AddOrEditMenuModal';
import type { ModalFormProps } from '@ant-design/pro-components';
import { isEmpty } from '@/utils';

const AuthManage: React.FC = () => {
  // const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  // const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [currentSelectMenu, setCurrentSelectMenu] = useState<{
    selectId: string;
    selectMenu: MENU.MenuType;
  }>();
  const [treeData, setTreeData] = useState<MENU.MenuType[]>([]);

  const loadMenuTree = () => {
    getMenuTree().then((res) => {
      if (res.success) {
        setTreeData(res.data);
      }
    });
  };

  useEffect(() => {
    loadMenuTree();
  }, []);

  const onSelect: TreeProps['onSelect'] = (selectedKeys, e) => {
    console.log('selected', selectedKeys, e);
    setCurrentSelectMenu({
      selectId: selectedKeys[0] as string,
      selectMenu: e.node as unknown as MENU.MenuType,
    });
  };
  const onAddMenu: ModalFormProps['onFinish'] = async (values) => {
    console.log('菜单信息', values);
    return addMenu({
      ...(values as MENU.AddMenuParams),
      pid: values.pid.at(-1) as string,
    })
      .then((res) => {
        if (res.success) {
          message.success('添加成功');
          loadMenuTree();
          return true;
        }
        return false;
      })
      .catch(() => {
        return false;
      });
  };

  const onEditMenu: ModalFormProps['onFinish'] = async (values) => {
    console.log('菜单信息 edit', values);
    return editMenu({
      ...(values as MENU.EditMenuParams),
      id: currentSelectMenu?.selectId as string,
      pid: currentSelectMenu?.selectMenu.pid as string,
    })
      .then((res) => {
        if (res.success) {
          message.success('编辑成功');
          loadMenuTree();
          return true;
        }
        return false;
      })
      .catch(() => {
        return false;
      });
  };

  const onDelMenu = () => {
    Modal.confirm({
      title: '温馨提示',
      content: '确认删除该菜单吗？',
      okType: 'danger',
      async onOk() {
        return deleteMenu({
          id: currentSelectMenu?.selectId as string,
          pid: currentSelectMenu?.selectMenu.pid as string,
        }).then((res) => {
          if (res.success) {
            message.success('删除成功');
            loadMenuTree();
          }
        });
      },
    });
  };

  return (
    <PageContainer>
      <Space align="center" style={{ marginBottom: 8 }}>
        <AddOrEditMenuModal
          actionType="add"
          treeData={treeData}
          triggerEl={<Button type="primary">新增菜单</Button>}
          onFinished={onAddMenu}
        />
        <AddOrEditMenuModal
          actionType="edit"
          treeData={treeData}
          triggerEl={
            <Button
              type="primary"
              onClick={(e) => {
                if (isEmpty(currentSelectMenu?.selectMenu)) {
                  message.info('请先选中待编辑的菜单项');
                  e.stopPropagation();
                  e.preventDefault();
                }
              }}
            >
              编辑菜单
            </Button>
          }
          onFinished={onEditMenu}
          editMenuInfo={currentSelectMenu?.selectMenu}
        />
        <Button type="primary" danger onClick={onDelMenu}>
          删除菜单
        </Button>
      </Space>
      <Tree
        showLine
        switcherIcon={<DownOutlined />}
        onSelect={onSelect}
        defaultExpandedKeys={treeData.map((item) => item.id)}
        // autoExpandParent={autoExpandParent}
        treeData={treeData}
        fieldNames={{ title: 'menuName', key: 'id' }}
      />
    </PageContainer>
  );
};

export default AuthManage;
